import { accountLoginRequest, getUserInfoById, getUserMenuById } from '@/service/login'
import { defineStore } from 'pinia'
import type { IAccount } from '@/types'
import { localCache } from '@/utils/cache'
import router from '@/router'
import { TOKEN } from '@/global/constants'
import { mapMenusToRouter } from '@/utils/map-menus'

const userLoginStore = defineStore('login', {
  state: (): any => ({
    token: '',
    userInfo: {},
    userMenu: [],
  }),
  actions: {
    async loginAccountAction(account: IAccount) {
      const loginData: any = await accountLoginRequest(account)
      console.log(loginData.data)
      const id = loginData.data.userInfo.id
      const name = loginData.data.userInfo.name
      this.token = loginData.data.token

      //进行本地缓存
      localCache.setCache(TOKEN, this.token)

      //获取登录用户的详细信息
      const userInfoResult: any = await getUserInfoById(id)
      this.userInfo = userInfoResult.data

      const userMenuResult: any = await getUserMenuById(this.userInfo.data.role.id)
      this.userMenu = userMenuResult.data

      //进行本地缓存
      localCache.setCache('userInfo', this.userInfo)
      localCache.setCache('userMenu', this.userMenu)

      const routes = mapMenusToRouter(userMenuResult.data.data)
      routes.forEach((route) => {
        router.addRoute('home', route)
      })

      router.push('/home')
    },
    loadLocalCacheAction() {
      const token = localCache.getCache(TOKEN)
      const userInfo = localCache.getCache('userInfo')
      const userMenu = localCache.getCache('userMenu')
      if (token && userInfo && userMenu) {
        this.token = token
        this.userInfo = userInfo
        this.userMenu = userMenu

        const routes = mapMenusToRouter(userMenu.data)
        routes.forEach((route) => {
          router.addRoute('home', route)
        })
      }
    },
  },
})

export default userLoginStore
